<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { debounce } from "lodash-es";
import { useRouter, useRoute } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
import { ElNotification } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";
import PasswordStrength from "@/components/ui/PasswordStrength.vue";

type Title = "Error" | "Success";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 自定义验证规则：确认密码必须与密码一致
const validateConfirmPassword = (_rule: any, value: any, callback: any) => {
  console.log("", value, registerForm.password);
  if (value !== registerForm.password) {
    callback(new Error("两次输入的密码不一致！"));
  } else {
    callback();
  }
};

const registerRules = reactive({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 4, max: 16, message: "长度在 4 到 16 个字符", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: "用户名只能包含字母、数字和下划线",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度至少为6位", trigger: "blur" },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/,
      message: "必须包含大小写字母和数字",
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      type: "email",
      message: "请输入有效的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的手机号",
      trigger: "blur",
    },
  ],
  captcha: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 6, message: "验证码长度为6位", trigger: "blur" },
  ],
});
const registerForm = reactive({
  username: "admin",
  password: "123456Ns",
  confirmPassword: "123456Ns",
  email: "s@163.com",
  phone: "18701418223",
  captcha: "123423",
});
const checkAgreement = ref(false);
const agreementError = ref(false);
const loading = ref(false);
const registerFormRef = ref();

onMounted(() => {});

// 提交，添加防抖
const onSubmit = debounce(async () => {
  console.log("submit", registerFormRef.value);
  registerFormRef.value
    ?.validate()
    .then(() => {
      // 验证成功
      if (!checkAgreement.value) {
        agreementError.value = true;
        onHandleMessage("Error", "请同意隐私政策和条款", "error");
        return true;
      }
      // 检测通过
      handleRegister();
    })
    .catch((error: any) => {
      // error 对象包含详细错误信息
      console.log("验证失败字段:", error.fields);
      console.log("完整错误对象:", error);
      throw error;
    });
  return;
}, 350);

const handleRegister = async () => {
  console.log("注册中...");
  loading.value = true;
  try {
    const { confirmPassword, ...submitData } = registerForm;
    console.log("注册参数", submitData);
    const res = await userStore.register({ ...submitData });
    console.log("success", res);
    if (res) {
      onHandleMessage("Success", "注册成功", "success");
      // return;
      setTimeout(() => {
        loading.value = false;
        const redirect = route.query.redirect || "/";
        console.log("redirect", redirect);
        router.push(redirect as string);
      }, 230);
    } else {
      // onHandleMessage("Error", "用户名或密码错误", "error");
      onReset(); // 重置验证状态
    }
  } catch (error: any) {
    console.log(error);
    loading.value = false;
    onHandleMessage("Error", error.message || "注册失败", "error");
    onReset(); // 重置验证状态
  } finally {
    loading.value = false;
  }
};

const strengthLevel = ref(0);
const handleStrengthChange = (level: number) => {
  strengthLevel.value = level;
};
const onHandleMessage = (title: string, msg: string, type: string) => {
  ElNotification({
    title: title,
    message: msg,
    type: type,
  } as any);
};
const onReset = () => {
  // --重置状态，暂留
};
</script>
<template>
  <div class="auth-box">
    <div class="p-t"></div>
    <el-form
      ref="registerFormRef"
      :model="registerForm"
      :rules="registerRules"
      class="auth-form"
    >
      <div class="title left">
        <h3 class="text-left">创建一个账号</h3>
        <span class="text-sm text-left opacity-70">让您的应用程序管理变得简单而有趣</span>
      </div>
      <el-form-item prop="username" class="pb-1.5">
        <el-input
          v-model="registerForm.username"
          placeholder="用户名"
          size="large"
          :prefix-icon="User"
        />
      </el-form-item>
      <!-- <el-form-item prop="password" class="pb-1.5">
        <el-input
          v-model="registerForm.password"
          type="password"
          placeholder="密码"
          size="large"
          :prefix-icon="Lock"
          show-password
        />
      </el-form-item> -->
      <el-form-item prop="password" class="pb-1.5">
        <PasswordStrength
          v-model="registerForm.password"
          @strength-change="handleStrengthChange"
        />
      </el-form-item>
      <el-form-item prop="confirmPassword" class="pb-1.5">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          placeholder="确认密码"
          size="large"
          :prefix-icon="Lock"
          show-password
          @keyup.enter="handleRegister"
        />
      </el-form-item>
      <el-form-item>
        <div class="flex items-center w-full">
          <el-checkbox v-model="checkAgreement" class="pr-1.5">我同意</el-checkbox>
          <router-link to="/forget" class="text-blue text-sm"
            >隐私政策 & 条款</router-link
          >
        </div>
        <div class="el-form-item__error" v-if="!checkAgreement && agreementError">
          请同意隐私政策和条款
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          class="submit-btn mx-auto mt-5"
          @click="onSubmit"
        >
          注册
        </el-button>
      </el-form-item>
    </el-form>
    <div class="flex justify-center">
      <span class="text-sm pr-1.5 text-white">已有账号? </span>
      <router-link to="/login" class="text-blue text-sm">去登录</router-link>
    </div>
    <div class="h-10"></div>
    <div class="p-b"></div>
  </div>
</template>

<style lang="scss" scoped>
@use '@/styles/layout/auth.scss';
:root {
  --text-color-primary: #fff !important;
}

.text-white {
  color: #fff !important;
}
.text-blue {
  color: #409eff !important;
}
:deep(.el-checkbox__label) {
  --el-checkbox-checked-text-color: #fff;
  color: #fff;
}
:deep(.el-popper) {
  color: #fff !important;
}
</style>
